# -*- coding: utf-8 -*-
'''
    :file: admin.py
    :author: -Farmer
    :url: https://blog.farmer233.top
    :date: 2021/03/21 18:47:52
'''
from logging import log

from app.utils import make_res
from flask import Blueprint, g, current_app, request
from flask_restful import Api, Resource
from app.extensions import auth
from app.models import User
from app.ddns import DDNSCore, DDNSConfig
from app.operation.Sysmessage import BaseMsg, DynamicMsg, SystemLogMsg
from app.operation.files import FileOperation
from app.operation.schema import LogMsgSchema

admin_bp = Blueprint('admin', __name__)
api = Api(admin_bp)

# 管理员登录测试接口
class AdminLoginTest(Resource):
    decorators = [auth.login_required]

    def get(self):
        # print(g.get('power'), type(g.get('power')))
        if not g.get('power') > 0:
            return make_res(message='账号没有权限'), 401
        return make_res(message='User is admin.')
    
    def post(self):
        return self.get()

# 管理员登录接口
class AdminLogin(Resource):
    def post(self):
        try:
            req_data = request.get_json()
            username = req_data.get("username")
            password = req_data.get("password")
            expiration = req_data.get('expiration')
            token = self.login(username, password, expiration)
            return make_res(data={
                "username": username,
                "token": token
            })
        except ValueError as e:
            return make_res(code=-1, message=str(e))
        except Exception as e:
            current_app.logger.warning(e)
            return make_res(code=-9), 500
    # 登录方法
    def login(self, username, password, expiration=600):
        if username is None or password is None:
            raise ValueError("用户名或密码未输入")

        user = User.query.filter(User.username == username).first()
        if user is None:
            raise ValueError("用户未注册")
        if not user.validate_password(password):
            raise ValueError("密码不正确")
        else:
            if user.power > 0:
                token = user.generate_admin_token(expiration)
                return token
            else:
                raise ValueError('该账号权限不足')


class AdminGetInfo(Resource):
    pass

# 阿里云DDNS web控制台接口
class ALiDDNS(Resource):
    decorators = [auth.login_required]
    
    def get(self):
        ''' get方法控制ddns启停，获取运行状态 '''
        try:
            if not g.get('power') > 0:
                return make_res(message='账号没有权限'), 401
            status = request.args.get('trigger', 'state')
            ddns_core = DDNSCore()
            if status == 'start':
                core_msg = ddns_core.run()
                return make_res(message=core_msg)
            if status == 'state':
                core_msg = ddns_core.state()
                return make_res(message=core_msg)
            core_msg = ddns_core.stop()
            return make_res(message=core_msg)
        except Exception as e:
            return make_res(message=str(e))

    def post(self):
        ''' post方法设置ddns配置 '''
        if not g.get('power') > 0:
            return make_res(message='账号没有权限'), 401
        try:
            req = request.get_json()
            access_key = req.get('accessKeyId')
            access_sec = req.get('accessSecret')
            domain_name = req.get('domain_name')
            rr_list = req.get('rr_list')
            DDNSConfig(access_key, access_sec, domain_name, rr_list)
            return make_res(message=f'set conf success.')
        except Exception as e:
            print(type(e))
            return make_res(code=-9, message=str(e))

# 获取服务器运行状态
class GetServerMsg(Resource):
    decorators = [auth.login_required]

    def get(self):
        '''
            get方法获取动态信息
            get方法可以减少网络开销
        '''
        if not g.get('power') > 0:
            return make_res(message='账号没有权限'), 401
        msg = DynamicMsg()
        res = msg.get_dynamic_msg()

        return make_res(data=res)


    def post(self):
        ''' post方法获取静态信息 '''
        try:
            if not g.get('power') > 0:
                return make_res(message='账号没有权限'), 401
            msg = BaseMsg()
            re_msg = {
                "cpuInfo": msg.get_cpu_core(),
                "memoryInfo": msg.get_memory(),
                "diskInfo": msg.get_disk_msg()
            }
            return make_res(data=re_msg)
        except ValueError as e:
            return make_res(code=-2, msg="获取信息失败")
        except Exception as err:
            return make_res(code=-9, msg='error')


# 获取日志信息接口
class GetLogMsg(Resource):
    decorators = [auth.login_required]
    def get(self):
        try:
            page_number = request.args.get('page', 1, type=int)
            per_page = request.args.get('per_page', 30, type=int)
            logs = SystemLogMsg.get(page=page_number, per_page=per_page)
            res = self.schema(logs.items)
            return make_res(data={
                "has_prev": logs.has_prev,
                "has_next": logs.has_next,
                "prev_num": logs.prev_num,
                "next_num": logs.next_num,
                "pages": logs.pages,
                "items": res
            })
        except Exception as e:
            current_app.logger.warning(e)
            print(e)
            return make_res(message=str(e))
    
    def schema(self, items):
        log_schema = LogMsgSchema(many=True)
        res = log_schema.dump(items)
        return res

        

api.add_resource(AdminLoginTest, '/admin_test')
api.add_resource(AdminLogin, '/admin_login')
api.add_resource(ALiDDNS, '/aliddns')
api.add_resource(GetServerMsg, '/getInfo')
api.add_resource(GetLogMsg, "/getLog")
